package com.mantou.mantouaiagent.config.springsecurity;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.task.DelegatingSecurityContextAsyncTaskExecutor;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.Executor;

/**
 * @auther zzyy
 * @create 2024-12-22 17:45
 */
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Resource
    private LoginAuthenticationFilter loginAuthenticationFilter;

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOriginPatterns(Collections.singletonList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type", "Accept", "X-Requested-With"));
        configuration.setExposedHeaders(Arrays.asList("Authorization"));
        configuration.setAllowCredentials(true);
        configuration.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                // 启用 CORS
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))
                // 禁用明文验证
                .httpBasic(AbstractHttpConfigurer::disable)
                // 禁用 CSRF 验证
                .csrf(AbstractHttpConfigurer::disable)
                // 禁用默认登录页
                .formLogin(AbstractHttpConfigurer::disable)
                // 禁用默认注销页
                .logout(AbstractHttpConfigurer::disable)
                // 禁用默认 Header（支持 iframe 访问页面）
                .headers(AbstractHttpConfigurer::disable)
                // 禁用 Session（项目中是使用 JWT 认证，不再是session了）
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 允许访问的url资源,白名单放行url-list
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 允许所有 OPTIONS 请求
                        .requestMatchers(
                                "/layui/**",
                                "/js/**",
                                "/css/**",
                                "/login.html",
                                "/index.html",
                                "/login2.html",
                                "/index2.html",
                                "/register.html",
                                "/register2.html",
                                "/user/login",
                                "/user/register",
                                "/user/exist",
                                "/captcha/create",
                                "/tongyi/chat",
                                "/tongyi/draw",
                                "/discuss/list",
                                "/kafka/**",
                                "/swagger-ui/**",
                                "/v3/**",
                                "/doc.html",
                                "/webjars/**",
                                "/ai/love_app/chat/sse/emitter",
                                "/ai/manus/chat/**"//允许访问 AI 相关接口
                                ).permitAll()
                        .anyRequest().authenticated() // 其他请求都需要认证
                )
                // 添加自定义登录认证过滤器，作用是引入JWT并融合进springsecurity
                .addFilterBefore(loginAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                .build();
    }
}
